<template>
  <el-dialog
    v-el-drag-dialog
    class="OrderDetailDialog"
    :title="titleText(type)"
    :visible.sync="isShow"
    width="1000px"
    @closed="close"
  >
    <el-form ref="dataForm" :model="form" label-position="right" label-width="100px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="单号:" prop="billCode">
            <el-input v-model="form.billCode" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="本期账单截至日期:" prop="endDt" label-width="140px">
            <el-date-picker
              v-model="form.endDt"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="客户编号:" prop="csmCode">
            <el-input v-model="form.csmCode" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户名称:" prop="csmName" label-width="140px">
            <el-input v-model="form.csmName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话:" prop="csmPhone">
            <el-input v-model="form.csmPhone" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="详细地址:" prop="csmAddress">
            <el-input v-model="form.csmAddress" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="备注:" prop="remark" label-width="140px">
            <el-input v-model.trim="form.remark" :disabled="type !== 1" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="OrderDetailDialog-calculate">
        <el-row>
          <el-col :span="6">
            <label class="calculate_label">上期期初结转：</label>{{ Number(form.prePending).toFixed(2) }}
          </el-col>
          <el-col :span="3" class="tc">+</el-col>
          <el-col :span="6">
            <label class="calculate_label"> 本期新增账款：</label>{{ Number(form.receivables || 0 - form.prePending || 0).toFixed(2) }}
          </el-col>
          <el-col :span="3" class="tc">=</el-col>
          <el-col :span="6">
            <label class="calculate_label"> 本期应收：</label>{{ Number(form.receivables).toFixed(2) }}
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="9">
            <label class="calculate_label"> 本期已核销： </label>{{ Number(form.payments).toFixed(2) }}
          </el-col>
          <el-col :span="9">
            <label class="calculate_label"> 本期剩余待核销：</label>{{
              form.receivables - form.payments > 0
                ? (form.receivables - form.payments).toFixed(2)
                : "0.00"
            }}
          </el-col>
        </el-row>
      </div>
      <div class="OrderDetailDialog-btns mb10">
        <el-button
          v-if="type === 1"
          type="primary"
          @click="pushTableData"
        >录入核销账款</el-button>
        <el-button
          class="textBtn"
          type="text"
          @click="openReceiptsDetailDialog"
        >查看单据明细</el-button>
      </div>
      <lb-table
        ref="hxLbTable"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="column"
        :data="tableData"
        show-summary
        :summary-method="getSummaries"
        :immediate-fetch="false"
        @fetch="fetchData"
      />
      <el-row class="mt20">
        <el-col :span="8">
          <el-form-item label="制单人:" prop="operator">
            <el-input v-model="form.operator" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制单日期:" prop="createTime" label-width="140px">
            <el-date-picker
              v-model="form.createTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <div class="dialog-footer_right">
        <template v-if="type === 1">
          <el-button type="primary" @click="save"> 保存 </el-button>
          <el-button type="primary" @click="submitXd"> 提交销单 </el-button>
          <el-button type="primary" @click="cancellation"> 作废 </el-button>
        </template>
        <template v-else-if="type === 2">
          <el-button type="primary" @click="xiaodan"> 销单 </el-button>
          <el-button type="primary" @click="reject"> 驳回 </el-button>
        </template>

        <el-button @click="close"> 关闭 </el-button>
      </div>

      <div
        v-if="(type === 1 || type === 2) && pageInfo.total > 1"
        class="dialog-footer_left"
      >
        <span
          class="mr10"
        >共 {{ `${pageInfo.currentPage} / ${pageInfo.total} ` }}单</span>
        <el-button
          type="text"
          :disabled="pageInfo.currentPage === 1"
          class="f16"
          @click="pageTurning('previous')"
        >
          上一单
        </el-button>
        <el-button
          type="text"
          :disabled="pageInfo.currentPage === pageInfo.total"
          class="f16"
          @click="pageTurning('next')"
        >
          下一单
        </el-button>
      </div>
    </div>

    <ReceiptsDetailDialog ref="ReceiptsDetailDialogRef" />
    <XiaoDanDialog ref="XiaoDanDialogRef" @submit="xiaodanSubmit" />
  </el-dialog>
</template>

<script>
  import {
    queryMonthAccCsmMonthlyBillList,
    monthAccCsmMonthlyHexiaoSave,
    monthAccCsmMonthlyHexiaoApply,
    monthAccCsmMonthlyInvalid,
    monthAccCsmMonthlyXiaodan,
    queryMonthAccCsmDetail,
    queryMonthAccCsmBillInfoDetail
  } from '@/api'
  import dayjs from 'dayjs'
  import ReceiptsDetailDialog from './ReceiptsDetailDialog.vue'
  import XiaoDanDialog from './XiaoDanDialog.vue'
  export default {
    components: {
      ReceiptsDetailDialog,
      XiaoDanDialog
    },
    data() {
      return {
        isShow: false,
        form: {
          billCode: '', // 单号
          endDt: '', // 本期账单截至日
          csmCode: '', // 客户编号
          csmName: '', // 客户名称
          csmPhone: '', // 联系电话
          csmAddress: '', // 详细地址
          remark: '', // 备注
          prePending: '0.00', // 上期期初结转
          // newReceivables: "0.00",
          receivables: '0.00', // 本期应收
          payments: '0.00', // 本期已核销
          // waitPayments: "0.00", // 本期剩余待核销
          operator: '', // 制单人
          createTime: '', // 制单日期
          orgNameIDS: ''
        },
        type: 1, // 1核销 2销单 3查看
        tableData: [],
        tableDataDeletes: [],
        tableDataOrigin: [],
        pageInfo: {
          currentPage: 1,
          total: 1
        },
        rowData: {},

        payMethodOptions: [
          {
            label: '现金',
            value: 1
          },
          {
            label: '银行转账',
            value: 2
          },
          {
            label: '支票',
            value: 3
          },
          {
            label: '微信',
            value: 4
          },
          {
            label: '支付宝',
            value: 5
          },
          {
            label: '券',
            value: 6
          }
        ]
      }
    },
    computed: {
      column() {
        const column = [
          {
            type: 'index'
          },
          {
            label: '收款方式',
            prop: 'payMethod',
            width: 100,
            align: 'center',
            render: (h, scope) => {
              return (
              <div>
                {scope.row._edit ? (
                  <el-select
                    value={scope.row[scope.column.property]}
                    placeholder='请选择'
                    onChange={(val) => {
                      scope.row[scope.column.property] = val
                    }}
                  >
                    {this.payMethodOptions.map((option) => {
                      return (
                        <el-option label={option.label} value={option.value}></el-option>
                      )
                    })}
                  </el-select>
                ) : (
                  <span>{this.payMethodFormat(scope.row[scope.column.property])}</span>
                )}
              </div>
              )
            }
          },
          {
            label: '收款日期',
            prop: 'happendDt',
            width: 160,
            align: 'center',
            render: (h, scope) => {
              return (
              <div>
                {scope.row._edit ? (
                  <el-date-picker
                    value={scope.row[scope.column.property]}
                    type='date'
                    value-format='yyyy-MM-dd'
                    placeholder='选择日期'
                    style='width: 140px'
                    onInput={(val) => {
                      scope.row[scope.column.property] = val
                    }}
                  ></el-date-picker>
                ) : (
                  <span>
                    {scope.row[scope.column.property] &&
                      dayjs(scope.row[scope.column.property]).format('YYYY-MM-DD')}
                  </span>
                )}
              </div>
              )
            }
          },
          {
            label: '收款人',
            prop: 'payee',
            width: 80,
            align: 'center',
            render: (h, scope) => {
              return (
              <div>
                {scope.row._edit ? (
                  <el-input
                    onInput={(val) => {
                      scope.row[scope.column.property] = val
                    }}
                    value={scope.row[scope.column.property]}
                  ></el-input>
                ) : (
                  <span>{scope.row[scope.column.property]}</span>
                )}
              </div>
              )
            }
          },
          {
            label: '付款账户',
            prop: 'payAccount',
            width: 120,
            align: 'center',
            render: (h, scope) => {
              return (
              <div>
                {scope.row._edit ? (
                  <el-input
                    onInput={(val) => {
                      scope.row[scope.column.property] = val
                    }}
                    value={scope.row[scope.column.property]}
                  ></el-input>
                ) : (
                  <span>{scope.row[scope.column.property]}</span>
                )}
              </div>
              )
            }
          },
          {
            label: '收款账户',
            prop: 'collAccount',
            width: 120,
            align: 'center',
            render: (h, scope) => {
              return (
              <div>
                {scope.row._edit ? (
                  <el-input
                    onInput={(val) => {
                      scope.row[scope.column.property] = val
                    }}
                    value={scope.row[scope.column.property]}
                  ></el-input>
                ) : (
                  <span>{scope.row[scope.column.property]}</span>
                )}
              </div>
              )
            }
          },
          {
            label: '金额',
            prop: 'amount',
            width: 80,
            align: 'right',
            render: (h, scope) => {
              return (
              <div>
                {scope.row._edit ? (
                  <el-input
                    value={scope.row[scope.column.property]}
                    onInput={(val) => {
                      scope.row[scope.column.property] = val.replace(/[^\d.]/g, '')
                    }}
                  ></el-input>
                ) : (
                  <span>
                    {scope.row[scope.column.property] &&
                      Number(scope.row[scope.column.property]).toFixed(2)}
                  </span>
                )}
              </div>
              )
            }
          },
          {
            label: '备注',
            prop: 'remark',
            align: 'center',
            render: (h, scope) => {
              return (
              <div>
                {scope.row._edit ? (
                  <el-input
                    onInput={(val) => {
                      scope.row[scope.column.property] = val
                    }}
                    value={scope.row[scope.column.property]}
                  ></el-input>
                ) : (
                  <span>{scope.row[scope.column.property]}</span>
                )}
              </div>
              )
            }
          },
          {
            label: '操作',
            width: 145,
            fixed: 'right',
            align: 'center',
            render: (h, scope) => {
              return (
              <div>
                {scope.row._edit ? (
                  <el-link
                    type='primary'
                    onClick={() => {
                      this.handleSave(scope)
                    }}
                  >
                    结束编辑
                  </el-link>
                ) : (
                  <el-link
                    type='primary'
                    onClick={() => {
                      this.handleEdit(scope)
                    }}
                  >
                    编辑
                  </el-link>
                )}
                <el-link
                  size='mini'
                  underline={false}
                  type='danger'
                  onClick={() => this.del(scope.row._index)}
                >
                  删除
                </el-link>
              </div>
              )
            }
          }
        ]
        if (this.type === 1) return column
        else {
          // 核销的时候才有弹窗
          column.pop()
          return column
        }
      }
    },
    methods: {
      show(type, row) {
        this.isShow = true
        this.type = type
        this.rowData = row

        if ((this, type === 3)) this.getDetailData()
        else this.fetchData({ currentPage: 1, pageSize: 1 })
      },
      close() {
        this.isShow = false
        this.tableData = []
        this.tableDataDeletes = []
        this.$refs['dataForm'].resetFields()
      },
      titleText(val) {
        switch (val) {
        case 1:
          return `核销结款单--${this.form.orgNameIDS}`
        case 2:
          return `销单--${this.form.orgNameIDS}`
        case 3:
          return `结款单明细--${this.form.orgNameIDS}`
        }
      },
      pushTableData() {
        const defalutData = {
          payMethod: 1,
          happendDt: new Date(),
          payee: '',
          payAccount: '',
          collAccount: '',
          amount: '',
          remark: '',
          _edit: true,
          _index: this.tableData.length
        }
        this.tableData.push(defalutData)
      },
      openReceiptsDetailDialog() {
        if (!this.form.billCode) {
          this.$message.error('没有单号，无法查看单据明细')
          return
        }
        this.$refs['ReceiptsDetailDialogRef'].show(this.form.billCode)
      },
      async getDetailData() {
        const params = {
          billCode: this.rowData.billCode
        }
        const { status, data } = await queryMonthAccCsmBillInfoDetail(params)
        if (status === 200) {
          // const rowsOne = data[0];
          // this.tableData = rowsOne.payRecordList;
          this.initFormData(data)
          this.getDetailTableData()
        }
      },
      async getDetailTableData() {
        const params = {
          billCode: this.rowData.billCode
        }
        const { status, data } = await queryMonthAccCsmDetail(params)
        if (status === 200) {
          this.tableData = data
        }
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          currentPage,
          pageSize,
          csmId: this.rowData.csmId,
          billStatus: this.type === 1 ? 20 : 30 // 账款追踪20   销单 30
        }
        const res = await queryMonthAccCsmMonthlyBillList(query)
        if (res.status === 200) {
          this.pageInfo.total = res.data.total
          if (res.data.rows.length) {
            const rowsOne = res.data.rows[0]
            this.tableData = rowsOne.payRecordList.map((v, index) => {
              return {
                ...v,
                _index: index
              }
            })
            this.tableDataOrigin = rowsOne.payRecordList
            this.initFormData(rowsOne)
          }
        }
      },
      // 初始化表单数据
      initFormData(data) {
        for (const key in this.form) {
          if (data[key]) this.form[key] = data[key]
        }
      },
      // 合计方法
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          const noSumArray = [
            'remark',
            'payMethod',
            'collAccount',
            'payAccount',
            'payee',
            'happendDt'
          ]
          if (noSumArray.includes(column.property)) {
            return
          }
          const values = data.map((item) => Number(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        })
        sums[sums.length - 1] = Number(sums[sums.length - 1]).toFixed(2)
        return sums
      },
      payMethodFormat(val) {
        switch (val) {
        case 1:
          return '现金'
        case 2:
          return '银行转账'
        case 3:
          return '支票'
        case 4:
          return '微信'
        case 5:
          return '支付宝'
        case 6:
          return '券'
        }
      },
      // 结束编辑
      handleSave(scope) {
        for (let i = 0; i < this.tableData.length; i++) {
          const item = this.tableData[i]
          if (!item.amount) {
            this.$message.error('核销金额不能为空')
            return
          }
        }
        this.$set(scope.row, '_edit', false)
      },
      // 开启编辑
      handleEdit(scope) {
        this.$set(scope.row, '_edit', true)
      },
      // 删除数据
      del(index) {
        // 删除列表数据并标记放入删除数组中
        for (let i = 0; i < this.tableData.length; i++) {
          const v = this.tableData[i]
          if (v._index === index) {
            v.status = -1
            this.tableDataDeletes.push(v)
            this.tableData.splice(i, 1)
            break
          }
        }
      },
      // 保存
      async save(callback) {
        // 剔除添加后又删除的数据
        const payRecordJson = this.tableData.concat(this.tableDataDeletes).filter((v) => {
          return !(!v.recordId && v.status === -1)
        })

        const params = {
          payRecordJson: JSON.stringify(payRecordJson),
          billCode: this.form.billCode,
          remark: this.form.remark
        }

        const { status } = await monthAccCsmMonthlyHexiaoSave(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: `保存成功`,
            type: 'success',
            duration: 2000
          })

          if (typeof callback === 'function') callback()
          else {
            this.$emit('refresh')
            this.close()
          }
        }
      },
      // 提交销单
      submitXd() {
        const _this = this
        const innerFunc = async function() {
          const params = {
            billCode: _this.form.billCode
          }

          const { status } = await monthAccCsmMonthlyHexiaoApply(params)
          if (status === 200) {
            _this.$notify({
              title: '提示',
              message: `提交销单成功`,
              type: 'success',
              duration: 2000
            })
            _this.$emit('refresh')
            _this.close()
          }
        }

        // 提交保存后销单
        this.save(function() {
          innerFunc()
        })
      },
      // 作废
      cancellation() {
        this.$confirm(`确认要作废该单据吗？`, '提示', {
          type: 'warning'
        }).then(() => {
          this.cancellationSubmit()
        })
      },
      // 作废提交
      async cancellationSubmit() {
        const params = {
          billCode: this.form.billCode
        }
        const { status } = await monthAccCsmMonthlyInvalid(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: `作废成功`,
            type: 'success',
            duration: 2000
          })
          this.$emit('refresh')
          this.close()
        }
      },
      //  销单
      xiaodan() {
        const money = (this.form.receivables - this.form.payments).toFixed(2)
        this.$refs['XiaoDanDialogRef'].show(this.form.billCode, money)
      },
      reject() {
        const data = {
          type: 1,
          orgId: this.rowData.orgId
        }
        this.xiaodanSubmit(data)
      },
      async xiaodanSubmit(data) {
        let type, billStatus

        switch (data.type) {
        case 1: // 驳回
          type = 0
          billStatus = 40
          break
        case 2: // 结转差额
          type = 2
          billStatus = 0
          break
        case 3: // 减免上报
          type = 30
          billStatus = 0
          break
        case 4: // 减免差额
          type = 3
          billStatus = 0
          break
        }
        const params = {
          billCode: this.form.billCode,
          orgId: data.orgId,
          type: type,
          billStatus: billStatus
        }
        const { status } = await monthAccCsmMonthlyXiaodan(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: `操作成功`,
            type: 'success',
            duration: 2000
          })
          this.$emit('refresh')
          this.close()
        }
      },

      // 翻页
      pageTurning(type) {
        if (type === 'previous') {
          // 上一单
          if (this.pageInfo.currentPage - 1 >= 1) {
            this.pageInfo.currentPage--
            this.fetchData({ currentPage: this.pageInfo.currentPage, pageSize: 1 })
          }
        } else {
          // 下一单
          if (this.pageInfo.currentPage + 1 <= this.pageInfo.total) {
            this.pageInfo.currentPage++
            this.fetchData({ currentPage: this.pageInfo.currentPage, pageSize: 1 })
          }
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.OrderDetailDialog {
  &-calculate {
    padding-left: 15px;
    margin-bottom: 10px;
    line-height: 30px;
    background: #ddd;

    .calculate_label {
      display: inline-block;
      width: 140px;
      text-align: right;
    }
  }
  &-btns {
    .textBtn {
      text-decoration: underline;
      // border-bottom: 1px solid #01999f;
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: space-between;
    flex-direction: row-reverse;
  }
}
</style>
